package com.javafactroy.kunlong.bip.icp.netty.client.service;


import com.alibaba.fastjson.JSONObject;
import com.javafactroy.kunlong.bip.icp.common.consts.IConfig;
import com.javafactroy.kunlong.bip.icp.netty.client.framework.DxpMsgSyncFuture;
import com.javafactroy.kunlong.bip.icp.netty.client.framework.DxpMsgSyncFutureMngr;
import com.javafactroy.kunlong.bip.icp.netty.client.framework.NettyClient;
import com.javafactroy.kunlong.bip.icp.netty.client.service.iface.INettyTcpClient;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.javafactroy.kunlong.bip.icp.common.config.BipConfig;
import com.javafactroy.kunlong.bip.icp.common.consts.EAppType;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;

//@Service
@Slf4j
@Data
@Component
public class NettyTcpClient implements INettyTcpClient {


    public NettyTcpClient() {

    }

    @Autowired
    private NettyClient nettyClient;
    @Autowired
    BipConfig bipConfig;

    //@PostConstruct
    public void start(EAppType appType) throws InterruptedException {
        nettyClient.setBipConfig(bipConfig);
        nettyClient.start(appType);
    }

    @Override
    public IMessage sendSyncMsg(IMessage message) {

        DxpMsgSyncFuture<IMessage> syncFuture = new DxpMsgSyncFuture<IMessage>();
        // 放入缓存中
        DxpMsgSyncFutureMngr.put(message.getMessageId() + "", syncFuture);
        // 发送同步消息
        IMessage iMessage = nettyClient.sendSyncMsg(message, syncFuture);
        if (iMessage.getMsgState() != null && iMessage.getMsgState() == IConfig.INettyConst.MSG_State.MSG_SEND_ERR) {
            iMessage = nettyClient.sendSyncMsg(message, syncFuture);
        }
        return iMessage;

    }


    @Override
    public String sendSyncMsg(String text, String dataId) {

        DxpMsgSyncFuture<String> syncFuture = new DxpMsgSyncFuture<String>();
        // 放入缓存中
        DxpMsgSyncFutureMngr.put(dataId, syncFuture);
        // 封装数据
        JSONObject object = new JSONObject();
        object.put("dataId", dataId);
        object.put("text", text);

        // 发送同步消息
        return nettyClient.sendSyncMsg(object.toJSONString(), syncFuture);
    }

    @Override
    public void setIpPort(String ip, int port) {
        this.nettyClient.setIpPort(ip, port);
    }


}

